<template>
  <!-- 页面标题 -->
  <view class="page-header">
    <text class="page-title">老师科目管理</text>
    <text class="page-subtitle">点击老师可编辑对应年级科目</text>
  </view>
  
  <!-- 老师列表 -->
  <scroll-view scroll-y class="teacher-list">
    <view 
      class="teacher-card" 
      v-for="teacher in teacherList" 
      :key="teacher.teacherId"
      @click="openEditDialog(teacher)"
    >
      <view class="teacher-header">
        <image class="avatar" src="/static/logo.png" mode="aspectFill"></image>
        <view class="teacher-info">
          <text class="teacher-name">{{teacher.name}}</text>
          <text class="teacher-phone">{{teacher.phone}}</text>
        </view>
        <uni-icons type="arrowright" size="20" color="#999"></uni-icons>
      </view>
      
      <view class="grades-section">
        <text class="section-title">授课年级</text>
        <view class="grade-list">
          <text 
            class="grade-tag" 
            v-for="(grade, index) in teacher.grades ? teacher.grades.split('，') : []" 
            :key="index"
          >
            {{grade.trim()}}
          </text>
          <text class="empty-tip" v-if="!teacher.grades">暂无授课年级</text>
        </view>
      </view>
    </view>
  </scroll-view>
  
  <!-- 编辑科目弹窗 -->
  <uni-popup ref="editPopup" type="dialog" class="edit-dialog">
    <view class="dialog-content">
      <view class="dialog-header">
        <text class="dialog-title">编辑 {{currentTeacher.name}} 的授课科目</text>
        <uni-icons 
          type="close" 
          size="20" 
          color="#999" 
          @click="closeEditDialog"
        ></uni-icons>
      </view>
      
      <view class="dialog-body">
        <!-- 年级选择 -->
        <view class="section">
          <text class="section-title">选择授课年级</text>
          <view class="grade-list">
            <view 
              class="grade-tag"
              v-for="(grade, index) in availableGrades"
              :key="index"
              :class="{active: selectedGrade === grade.value}"
              @click="selectGrade(grade.value)"
            >
              {{grade.name}}
            </view>
          </view>
        </view>
        
        <!-- 科目编辑区域 -->
        <view class="section" v-if="selectedGrade">
          <text class="section-title">编辑科目</text>
          
          <!-- 已选科目 -->
          <view class="selected-subjects" v-if="currentSubjects.length > 0">
            <text class="subtitle">已选科目</text>
            <view class="subject-list">
              <view 
                class="subject-tag selected"
                v-for="(subject, index) in currentSubjects"
                :key="index"
                @click="removeSubject(selectedGrade, subject)"
              >
                <text>{{subject}}</text>
                <uni-icons type="close" size="14" color="#fff"></uni-icons>
              </view>
            </view>
          </view>
          
          <!-- 可选科目 -->
          <view class="available-subjects" v-if="availableSubjects.length > 0">
            <text class="subtitle">可选科目</text>
            <view class="subject-list">
              <view 
                class="subject-tag available"
                v-for="(subject, index) in availableSubjects"
                :key="index"
                @click="addSubject(selectedGrade, subject)"
              >
                <text>{{subject}}</text>
                <uni-icons type="plus" size="14" color="#fff"></uni-icons>
              </view>
            </view>
          </view>
          
          <view class="empty-tip" v-if="availableSubjects.length === 0 && currentSubjects.length === 0">
            该年级暂无更多可选科目
          </view>
        </view>
      </view>
      
      <view class="dialog-footer">
        <button class="btn cancel" @click="closeEditDialog">取消</button>
        <button class="btn confirm" @click="submitSubjects">保存</button>
      </view>
    </view>
  </uni-popup>
</template>

<script>
	import {
		globalVariable
	} from '../../configMy.js';
export default {
  data() {
    return {
      teacherList: [],
      currentTeacher: {
        teacherId: null,
        name: '',
        grades: ''
      },
      teacherSubjectData: [], // 格式: [{grade: '一年级', subjects: ['语文', '数学']}]
      availableGrades: [],    // 动态生成
      selectedGrade: '',
      availableSubjects: [],  // 当前年级可选科目
      currentSubjects: [],    // 当前年级已选科目
      subjectColors: {
        '语文': '#FF6B81',
        '数学': '#4A8CFF',
        '英语': '#FFA500',
        '物理': '#9B59B6',
        '化学': '#2ECC71',
        '生物': '#1ABC9C',
        '历史': '#E74C3C',
        '地理': '#3498DB',
        '政治': '#F39C12'
      }
    }
  },
  onLoad() {
    this.fetchTeachers()
  },
  methods: {
    getSubjectColor(subject) {
      return this.subjectColors[subject.trim()] || '#4A8CFF'
    },
    async fetchTeachers() {
      try {
        const res = await uni.request({
          url: globalVariable+'/getAllTeachers',
          method: 'GET'
        })
        
        if (res.data.status === 1) {
          this.teacherList = res.data.data
        } else {
          uni.showToast({
            title: res.data.message,
            icon: 'none'
          })
        }
      } catch (error) {
        uni.showToast({
          title: '获取老师列表失败',
          icon: 'none'
        })
        console.error(error)
      }
    },
    async fetchTeacherSubjects(teacherId, grade) {
      try {
        const res = await uni.request({
          url: globalVariable+'/getTeacherSubject',
          method: 'GET',
          data: { 
            teacherId,
            grade 
          }
        })
        
        if (res.data.status === 1) {
          return res.data.data
        } else {
          uni.showToast({
            title: res.data.message,
            icon: 'none'
          })
          return []
        }
      } catch (error) {
        uni.showToast({
          title: '获取老师科目失败',
          icon: 'none'
        })
        console.error(error)
        return []
      }
    },
    async openEditDialog(teacher) {
      this.currentTeacher = { ...teacher }
      this.selectedGrade = ''
      this.teacherSubjectData = []
      this.availableSubjects = []
      this.currentSubjects = []
      
      // 处理老师的grades字段，生成availableGrades
      this.availableGrades = teacher.grades ? 
        teacher.grades.split('，').map(grade => ({
          name: grade.trim(),
          value: grade.trim()
        })) : []
      
      // 默认选中第一个年级
      if (this.availableGrades.length > 0) {
        await this.selectGrade(this.availableGrades[0].value)
      }
      
      this.$refs.editPopup.open()
    },
    closeEditDialog() {
      this.$refs.editPopup.close()
    },
    async selectGrade(grade) {
      this.selectedGrade = grade
      await this.loadSubjectsForGrade(grade)
    },
    async loadSubjectsForGrade(grade) {
      try {
        // 获取该年级所有可选科目
        const res = await uni.request({
          url: globalVariable+`/getSubjectByGrade?grade=${grade}`,
          method: 'GET'
        })
        
        if (res.data.status === 1) {
          const allSubjects = res.data.data.subjects.split(',')
          
          // 获取该老师在该年级已选的科目
          const teacherSubjects = await this.fetchTeacherSubjects(this.currentTeacher.teacherId, grade)
          const selectedSubjects = teacherSubjects.map(item => item.subject)
          
          // 设置数据
          this.currentSubjects = selectedSubjects
          this.availableSubjects = allSubjects.filter(subject => !selectedSubjects.includes(subject))
        } else {
          uni.showToast({
            title: res.data.message,
            icon: 'none'
          })
        }
      } catch (error) {
        uni.showToast({
          title: '获取科目列表失败',
          icon: 'none'
        })
        console.error(error)
      }
    },
    addSubject(grade, subject) {
      // 检查是否已存在该年级
      let gradeData = this.teacherSubjectData.find(item => item.grade === grade)
      
      if (!gradeData) {
        gradeData = {
          grade,
          subjects: []
        }
        this.teacherSubjectData.push(gradeData)
        
        // 更新老师年级字符串
        if (this.currentTeacher.grades) {
          this.currentTeacher.grades += `，${grade}`
        } else {
          this.currentTeacher.grades = grade
        }
      }
      
      // 添加科目
      if (!gradeData.subjects.includes(subject)) {
        gradeData.subjects.push(subject)
      }
      
      // 更新当前显示
      this.currentSubjects.push(subject)
      this.availableSubjects = this.availableSubjects.filter(item => item !== subject)
    },
    removeSubject(grade, subject) {
      const gradeData = this.teacherSubjectData.find(item => item.grade === grade)
      if (gradeData) {
        gradeData.subjects = gradeData.subjects.filter(item => item !== subject)
        
        // 如果该年级没有科目了，移除该年级
        if (gradeData.subjects.length === 0) {
          this.teacherSubjectData = this.teacherSubjectData.filter(item => item.grade !== grade)
          this.currentTeacher.grades = this.currentTeacher.grades.split('，')
            .filter(g => g.trim() !== grade)
            .join('，')
        }
      }
      
      // 更新当前显示
      this.currentSubjects = this.currentSubjects.filter(item => item !== subject)
      this.availableSubjects.push(subject)
    },
    async submitSubjects() {
      try {
        // 构造提交数据 - 只包含当前选中的年级和科目
        const submitData = {
          teacherId: this.currentTeacher.teacherId,
          teacherName: this.currentTeacher.name,
          grade: this.selectedGrade,
          subjects: this.currentSubjects // 直接使用当前显示的已选科目
        };
    
        // 发送请求
        const res = await uni.request({
          url: globalVariable+'/updateSubjectByTeacher',
          method: 'POST',
          data: submitData,
          header: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });
    
        if (res.data.status === 1) {
          uni.showToast({
            title: '更新成功',
            icon: 'success'
          });
          this.fetchTeachers();
          this.closeEditDialog();
        } else {
          uni.showToast({
            title: res[1].data.message || '更新失败',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.showToast({
          title: '更新失败：' + (error.message || '未知错误'),
          icon: 'none'
        });
        console.error(error);
      }
    }
  }
}
</script>

<style lang="scss" scoped>
	/* 新增的样式 */
	.grade-list {
	  display: flex;
	  flex-wrap: wrap;
	  gap: 12rpx;
	  margin-top: 20rpx;
	}
	
	.grade-tag {
	  background-color: #f0f0f0;
	  color: #666;
	  padding: 12rpx 24rpx;
	  border-radius: 50rpx;
	  font-size: 28rpx;
	  transition: all 0.2s;
	  
	  &.active {
	    background-color: #4a8cff;
	    color: #fff;
	  }
	}
	.container {
		padding: 0;
		min-height: 100vh;
		background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
	}

	/* 页面标题样式 */
	.page-header {
		padding: 30rpx 30rpx 20rpx;
		background: rgba(255, 255, 255, 0.9);
		border-bottom: 1px solid rgba(0, 0, 0, 0.1);

		.page-title {
			font-size: 40rpx;
			font-weight: bold;
			color: #333;
			display: block;
			margin-bottom: 10rpx;
		}

		.page-subtitle {
			font-size: 26rpx;
			color: #666;
		}
	}

	/* 老师列表样式 */
	.teacher-list {
		height: calc(100vh - 140rpx);
		padding: 20rpx;

		.teacher-card {
			background: #fff;
			border-radius: 16rpx;
			padding: 30rpx;
			margin-bottom: 20rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
			transition: all 0.2s ease;

			&:active {
				transform: translateY(2rpx);
				box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.03);
			}

			.teacher-header {
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;

				.avatar {
					width: 100rpx;
					height: 100rpx;
					border-radius: 50%;
					margin-right: 20rpx;
					border: 2px solid #f5f5f5;
				}

				.teacher-info {
					flex: 1;

					.teacher-name {
						font-size: 34rpx;
						font-weight: 600;
						color: #333;
						display: block;
						margin-bottom: 6rpx;
					}

					.teacher-phone {
						font-size: 26rpx;
						color: #666;
					}
				}
			}

			.section-title {
				font-size: 28rpx;
				color: #666;
				display: block;
				margin-bottom: 12rpx;
			}

			.grade-list {
				display: flex;
				flex-wrap: wrap;
				gap: 12rpx;

				.grade-tag {
					background-color: #e8f5e9;
					color: #2e7d32;
					padding: 6rpx 20rpx;
					border-radius: 50rpx;
					font-size: 26rpx;
				}

				.empty-tip {
					font-size: 26rpx;
					color: #ccc;
				}
			}
		}
	}

	/* 编辑弹窗样式 */
	.edit-dialog {
		.dialog-content {
			width: 90vw;
			max-width: 700rpx;
			background: #fff;
			border-radius: 24rpx;
			overflow: hidden;
			box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
			animation: dialogFadeIn 0.3s ease;

			.dialog-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 30rpx;
				border-bottom: 1px solid rgba(0, 0, 0, 0.1);

				.dialog-title {
					font-size: 34rpx;
					font-weight: 600;
					color: #333;
				}
			}

			.dialog-body {
				padding: 0 30rpx;
				max-height: 60vh;
				overflow-y: auto;

				.section {
					margin: 30rpx 0;

					.section-title {
						font-size: 30rpx;
						color: #333;
						margin-bottom: 20rpx;
						display: block;
						font-weight: 500;
					}

					.grade-selector {
						.selector-box {
							background-color: #f8f8f8;
							padding: 20rpx 24rpx;
							border-radius: 12rpx;
							display: flex;
							justify-content: space-between;
							align-items: center;

							.selector-text {
								font-size: 28rpx;
								color: #333;
							}
						}
					}

					.subtitle {
						font-size: 26rpx;
						color: #666;
						display: block;
						margin: 20rpx 0 12rpx;
					}

					.subject-list {
						display: flex;
						flex-wrap: wrap;
						gap: 12rpx;

						.subject-tag {
							padding: 10rpx 24rpx;
							border-radius: 50rpx;
							font-size: 26rpx;
							display: flex;
							align-items: center;

							&.selected {
								background-color: #4a8cff;
								color: #fff;
							}

							&.available {
								background-color: #2ecc71;
								color: #fff;
							}
						}
					}

					.empty-tip {
						font-size: 26rpx;
						color: #999;
						text-align: center;
						padding: 20rpx 0;
					}
				}
			}

			.dialog-footer {
				display: flex;
				padding: 20rpx 30rpx;
				border-top: 1px solid rgba(0, 0, 0, 0.1);
				justify-content: space-between;

				.btn {
					margin: 0;
					padding: 0 60rpx;
					height: 80rpx;
					line-height: 80rpx;
					font-size: 30rpx;
					border-radius: 40rpx;
					transition: all 0.2s ease;

					&:active {
						opacity: 0.8;
					}

					&.cancel {
						background-color: #f5f5f5;
						color: #666;
					}

					&.confirm {
						background-color: #4a8cff;
						color: #fff;
					}
				}
			}
		}
	}

	/* 弹窗动画 */
	@keyframes dialogFadeIn {
		from {
			opacity: 0;
			transform: translateY(50rpx);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}
</style>